#include "saledao.h"
#include"../utils/database.h"
#include"../poco/sale/saleSetMeal.h"
#include"QSqlQuery"
#include<QSqlRecord>
#include<QVariant>
#include<QSqlError>
#include<QBuffer>
#include<QDebug>
#include"../poco/sale/saleUnit.h"
#include"../poco/sale/saleWeight.h"
#include"../utils/salefectory.h"

SaleDao::SaleDao()
{
    QSqlQuery result=QSqlQuery(*DataBase::getInstance());
}


////为窗口插入售卖的食物
//void SaleDao::insertSale(SaleBase* sale,WindowInfo win)
//{
//    sale->id=0;

//    //先将图片保存

//    QPixmap image=sale->image;
//    QByteArray bytes;
//    QBuffer buffer(&bytes);
//    buffer.open(QIODevice::WriteOnly);
//    image.save(&buffer, "PNG");
//    QVariant imageData(bytes);

//    QString sql="insert into picture(content,size)"
//                "value(:co,:si);";

//    result.prepare(sql);
//    result.bindValue(":co",imageData);
//    result.bindValue(":si",bytes.size());
//    if(!result.exec())
//    {
//        qDebug()<<result.lastError().text();
//    }
//    //获取上一个插入id
//    if(!result.exec("SELECT select @@id;"))
//        qDebug()<<result.lastError().text();
//    result.next();
//    int image_id=result.value(0).toInt();

//    //---------------------------------
//    sale->window_id=win.id;
//    if(sale->getClassType()==SaleBase::CLASS_SALEUNIT||
//            sale->getClassType()==SaleBase::CLASS_SALEWEIGHT)
//    {
//        //todo: 直接将salebase类中的所有数据插入到数据库 saleUnit表中

//        QString sql="insert into saleUnit("
//                    "id,window_id,name,price,status,diningType,unit,image_id,description,type) "
//                    "value(%1,%2,'%3',%4,%5,'%6','%7',%8,'%9',%10);";
//        sql=sql.arg(sale->id)
//               .arg(sale->window_id)
//                .arg(QString::fromStdString(sale->name))
//                .arg(sale->price)
//                .arg(sale->status)
//                .arg(QString::fromStdString(sale->diningType))
//                .arg(QString::fromStdString(sale->unit))
//                .arg(image_id)//image_id
//                .arg(QString::fromStdString(sale->desciption))
//                .arg(sale->class_type);

//        if(!result.exec(sql))
//        {
//             qDebug()<<result.lastError().text();
//        }

//    }
//    else
//    {
//        SaleSetMeal* meal=(SaleSetMeal*)sale;

//        for(unsigned int i=0;i<meal->nums.size();i++)
//        {
//            //先插入到setMeal数据中
//            QString sql="insert into setMeal("
//                        "set_id,window_id,name,price,status,num,unit,image_id,description) "
//                        "value(%1,%2,'%3',%4,%5,'%6','%7',%8,'%9',%10);";
//            sql=sql.arg(meal->id)
//                   .arg(meal->window_id)
//                    .arg(QString::fromStdString(meal->name))
//                    .arg(meal->price)
//                    .arg(meal->status)
//                    .arg(meal->nums[i])
//                    .arg(QString::fromStdString(meal->unit))
//                    .arg(image_id)//image_id
//                    .arg(QString::fromStdString(meal->desciption));
//            if(i==0)
//            {
//                if(!result.exec("SELECT select @@set_id;")){
//                        qDebug()<<result.lastError().text();
//                   };
//                result.next();
//                meal->id=result.value(0).toInt();
//            }
//            if(!result.exec("SELECT select @@type_id;"))
//                qDebug()<<result.lastError().text();
//            result.next();
//            meal->foodTypes[i].id=result.value(0).toInt();
//            for(auto fo:meal->foodTypes[i].foods)
//            {
//                //将某个类型的所有数据插入表foodtype
//                sql="insert into foodType(food_id,type_id,name) "
//                    "value(%1,%2,'%3');";
//                sql=sql.arg(fo->id).arg(meal->foodTypes[i].id).arg(QString::fromStdString(meal->foodTypes[i].name));
//                if(!result.exec(sql))
//                {
//                    qDebug()<<result.lastError().text();
//                }
//            }
//        }

//    }
//}


//为窗口插入售卖的食物
void SaleDao::insertSale(SaleBase* sale,WindowInfo win)
{
    sale->id=0;

    //先将图片保存

    QPixmap image=sale->image;
    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG");
    QVariant imageData(bytes);

    QString sql="insert into picture(content,size)"
                "value(0,:co,:si);";

    result.prepare(sql);
    result.bindValue(":co",imageData);
    result.bindValue(":si",bytes.size());
    if(!result.exec())
    {
        qDebug()<<result.lastError().text();
    }
    //获取上一个插入id
    if(!result.exec("select max(id) from picture;"))
        qDebug()<<result.lastError().text();
    result.next();
    int image_id=result.value(0).toInt();

    //---------------------------------

    {
        sale->window_id=win.id;
        // 直接将salebase类中的所有数据插入到数据库 saleUnit表中
             sql="insert into saleUnit("
                        "id,window_id,name,price,status,diningType,unit,image_id,description,type) "
                        "value(%1,%2,'%3',%4,%5,'%6','%7',%8,'%9',%10);";
            sql=sql.arg(sale->id)
                   .arg(sale->window_id)
                    .arg(QString::fromStdString(sale->name))
                    .arg(sale->price)
                    .arg(sale->status)
                    .arg(QString::fromStdString(sale->diningType))
                    .arg(QString::fromStdString(sale->unit))
                    .arg(image_id)//image_id
                    .arg(QString::fromStdString(sale->desciption))
                    .arg(sale->class_type);

            if(!result.exec(sql))
            {
                 qDebug()<<result.lastError().text();
            }

            if(!result.exec("SELECT  max(id) from picture;"))
                qDebug()<<result.lastError().text();
            result.next();
            sale->id=result.value(0).toInt()+1;
    }


    if(sale->getClassType()==SaleBase::CLASS_SALEUNIT||
            sale->getClassType()==SaleBase::CLASS_SALEWEIGHT)
    {


    }
    else
    {
        SaleSetMeal* meal=(SaleSetMeal*)sale;

        for(unsigned int i=0;i<meal->nums.size();i++)
        {
            meal->foodTypes[i].id=0;
            bool tag=true;
            for(auto fo:meal->foodTypes[i].foods)
            {
                //将某个类型的所有数据插入表foodtype
                sql="insert into foodType(food_id,type_id,name) "
                    "value(%1,%2,'%3');";
                sql=sql.arg(fo->id).arg(meal->foodTypes[i].id).arg(QString::fromStdString(meal->foodTypes[i].name));
                if(!result.exec(sql))
                {
                    qDebug()<<result.lastError().text();
                }
                if(tag)
                {
                    //第一次插入时自增，后面的插入不变
                    if(!result.exec("SELECT max(type_id) from foodType;"))
                        qDebug()<<result.lastError().text();
                    result.next();
                    meal->foodTypes[i].id=result.value(0).toInt();
                    tag=false;
                }
            }
            //-------------------------------------------
            //套餐数据插入到setFoodType数据中
            QString sql="insert into setFoodType "
                        "(set_id,type_id,num) "
                        "value(%1,%2,%3);";
            sql=sql.arg(meal->id).arg(meal->foodTypes[i].id).arg(meal->nums[i]);
        }

    }
}




//修改窗口中的某个食物
void SaleDao::alterSale(SaleBase*& sale)
{
    Q_UNUSED(sale);
}

//删除窗口中的某个食物
void SaleDao::delSale(SaleBase*& sale)
{
    if(sale->getClassType()==SaleBase::CLASS_SALEUNIT||
            sale->getClassType()==SaleBase::CLASS_SALEWEIGHT)
    {
        //根据id删除
        QString sql="delete from saleUnit where id = %1;";
        sql=sql.arg(sale->id);
        if(result.exec(sql))
         {

         }
         else
         {
                qDebug()<<result.lastError().text();
         }
    }
    else
    {


        //先删除类型表中的数据，
        QString sql="delete from foodType where type_id in (select type_id from setFoodType where set_id = %1 );";
        sql=sql.arg(sale->id);
        if(!result.exec(sql))
            qDebug()<<result.lastError().text();
        //根据id删除

        //删除套餐表setFoodType中数据
        sql="delete from setFoodType where set_id = %1";
        sql=sql.arg(sale->id);
        if(result.exec(sql))
         {

         }
         else
         {
                qDebug()<<result.lastError().text();
         }

        //根据id删除
        sql="delete from saleUnit where id = %1;";
        sql=sql.arg(sale->id);
        if(result.exec(sql))
         {

         }
         else
         {
                qDebug()<<result.lastError().text();
         }

    }
    //删除图片
    QString sql="delete from picture where id = %1;";
    sql=sql.arg(sale->id);
    if(result.exec(sql))
     {

     }
     else
     {
            qDebug()<<result.lastError().text();
     }
}

////查询单个数据，根据id,以及食物类型
//void SaleDao::selectSale(SaleBase* sale)
//{
//    if(sale->getClassType()==SaleBase::CLASS_SALEUNIT||
//            sale->getClassType()==SaleBase::CLASS_SALEWEIGHT)
//    {
//        //todo: 直查询表saleUnit

//        QString sql="select id,window_id,name,price,status,diningType,unit,image_id,description,type "
//                    "from saleUnit "
//                    "where id=%1;";
//        sql=sql.arg(sale->id);
//        if(!result.exec(sql))
//        {
//            qDebug()<<result.lastError().text();
//        }
//        int image_id;
//        result.next();
//        sale->class_type=result.value("type").toInt();
//        if(sale->class_type==SaleBase::CLASS_SALEUNIT)
//        {
//            delete sale;
//            sale=new SaleUnit;
//        }
//        else if(sale->class_type==SaleBase::CLASS_SALEWEIGHT)
//        {
//            delete sale;
//            sale=new SaleWeight;
//        }
//        sale->window_id=result.value("winow_id").toInt();
//        sale->name=result.value("name").toString().toStdString();
//        sale->price=result.value("price").toDouble();
//        sale->status=result.value("status").toInt();
//        sale->diningType=result.value("diningType").toString().toStdString();
//        sale->unit=result.value("unit").toString().toStdString();
//        image_id=result.value("image_id").toInt();
//        sale->desciption=result.value("description").toString().toStdString();

//        //获取图片

//        sql="select content from picture where id = %1;";
//        sql=sql.arg(image_id);
//        result.exec(sql);
//        result.next();
//        sale->image.loadFromData(result.value(0).toByteArray(),"png");
//    }
//    else
//    {
//        SaleSetMeal* meal=(SaleSetMeal*)sale;
//        //在setMeal表中查询基本信息
//        QString sql="select set_id,window_id,name,price,status,type_id,unit,image_id,description,num "
//                    "from saleUnit "
//                    "where id=%1;";
//        sql=sql.arg(sale->id);
//        if(!result.exec(sql))
//        {
//            qDebug()<<result.lastError().text();
//        }
//        int image_id;
//        while (result.next()) {

//            meal->window_id=result.value("winow_id").toInt();
//            meal->name=result.value("name").toString().toStdString();
//            meal->price=result.value("price").toDouble();
//            meal->status=result.value("status").toInt();
//            meal->unit=result.value("unit").toString().toStdString();
//            image_id=result.value("image_id").toInt();
//            meal->desciption=result.value("description").toString().toStdString();
//            int foodType_id,num;
//            foodType_id=result.value("type_id").toInt();
//            num=result.value("num").toInt();
//            string name;
//            //查询某个类型
//            vector<SaleBase*> foods=selectFoodType(foodType_id,name);
//            for(auto fo:foods)
//                selectSale(fo);
//            meal->foodTypes.push_back({foodType_id,name,foods});
//            meal->nums.push_back(num);
//        }
//    }
//}


//查询单个数据，根据id,以及食物类型
void SaleDao::selectSale(SaleBase*& sale)
{

        QSqlQuery result=QSqlQuery(*DataBase::getInstance());
        //todo: 直查询表saleUnit

        QString sql="select id,window_id,name,price,status,diningType,unit,image_id,description,type "
                    "from saleUnit "
                    "where id=%1;";
        sql=sql.arg(sale->id);
        if(!result.exec(sql))
        {
            qDebug()<<result.lastError().text();
        }
        int image_id;
        result.next();
        sale->class_type=result.value("type").toInt();
        int sale_id=sale->id;
        InitSaleFectory inFec;
        sale=inFec.CreateSale(sale->class_type);//生成对象
        if(sale==nullptr)
            sale=new SaleBase;
        sale->id=sale_id;
        sale->window_id=result.value("window_id").toInt();
        sale->name=result.value("name").toString().toStdString();
        sale->price=result.value("price").toDouble();
        sale->status=result.value("status").toInt();
        sale->diningType=result.value("diningType").toString().toStdString();
        sale->unit=result.value("unit").toString().toStdString();
        image_id=result.value("image_id").toInt();
        sale->desciption=result.value("description").toString().toStdString();

        //获取图片

        sql="select content from picture where id = %1;";
        sql=sql.arg(image_id);
        if(!result.exec(sql))
        {
            qDebug()<<result.lastError().text();
        }
        result.next();
        sale->image.loadFromData(result.value(0).toByteArray());


        if(sale->getClassType()==SaleBase::CLASS_SALESETMEAL)
        {
            SaleSetMeal* meal=(SaleSetMeal*)sale;
            //需要查表setFoodType
            QString sql="select type_id,num "
                        "from setFoodType "
                        "where set_id=%1;";
            sql=sql.arg(meal->id);
            result.exec(sql);
            while (result.next()) {
                int type_id=result.value("type_id").toInt();
                int num=result.value("num").toInt();
                string name;
                vector<SaleBase*> foods=selectFoodType(type_id,name);
                for(auto fo:foods)
                    selectSale(fo);
                meal->foodTypes.push_back({type_id,name,foods});
                meal->nums.push_back(num);
            }
            sale=meal;
        }
}



//查询某个类型的所有食物id
vector<SaleBase*> SaleDao::selectFoodType(int foodType_id,string &name)
{
    vector<SaleBase*> re;
    //查询foodType表
    QString sql="select food_id,name from foodType where type_id = %1;";
    sql=sql.arg(foodType_id);
    result.exec(sql);
    while (result.next()) {
        SaleBase* sale=new SaleUnit();
//        selectSale(sale);//查询食物
        sale->id=result.value("food_id").toInt();
        name=result.value("name").toString().toStdString();
        re.push_back(sale);
    }
    for(unsigned int i=0;i<re.size();i++)
    {
        selectSale(re[i]);
    }
    return re;
}


////查询指定窗口中的所有售卖食物，只需要有window_id即可
//vector<SaleBase*> SaleDao::selectAllSale(WindowInfo win)
//{
//    vector<SaleBase*> sales;
//    //查询saleUnit表中所有窗口数据，并且类型不为套餐类型 CLASS_SALESETMEAL

//    QString sql="select id from saleUnit where window_id = %1 ;";
//    sql=sql.arg(win.id);
//    result.exec(sql);
//    while (result.next()) {
//        SaleBase* sale=new SaleUnit();
//        sale->id=result.value("food_id").toInt();
//        selectSale(sale);
//        sales.push_back(sale);
//    }

//    //查询套餐setMeal中的所有数据
//    sql="select id from setMeal where window_id = %1 ;";
//    sql=sql.arg(win.id);
//    result.exec(sql);
//    while (result.next()) {
//        SaleBase* sale=new SaleSetMeal();
//        sale->id=result.value("food_id").toInt();
//        selectSale(sale);
//        sales.push_back(sale);
//    }
//    return sales;
//}


//查询指定窗口中的所有售卖食物，只需要有window_id即可
vector<SaleBase*> SaleDao::selectAllSale(WindowInfo win)
{
    vector<SaleBase*> sales;
    //查询saleUnit表中所有窗口数据，并且类型不为套餐类型 CLASS_SALESETMEAL

    QString sql="select id from saleUnit where window_id = %1 ;";
    sql=sql.arg(win.id);
    result.exec(sql);
    while (result.next()) {
        SaleBase* sale=new SaleUnit();
        sale->id=result.value("id").toInt();
//        selectSale(sale);
        sales.push_back(sale);
    }
    for(unsigned int i=0;i<sales.size();i++)
    {
        selectSale(sales[i]);
    }
    return sales;
}

//菜品审批，相当于修改表中的status值
bool SaleDao::examFood(SaleBase* sale,int status)
{
        //更改saleUnit表
        QString sql="update saleUnit set status = %1 where id= %2;";
        sql=sql.arg(status).arg(sale->id);
        if(!result.exec(sql))
        {
            qDebug()<<result.lastError().text();
            return false;
        }
    return true;
}
